package portal.dao;

import beans.*;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import portal.beans.Job;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

public class JobFileUploadDao {
	private HttpServletRequest request;
    private long maxSize = -1;
    private boolean isSuccess = true;
    private String SAVE_PATH;

    public JobFileUploadDao(HttpServletRequest request, HttpServletResponse response, long maxSize, String SAVE_PATH) {
        this.request = request;
        this.maxSize = maxSize;
        this.SAVE_PATH = SAVE_PATH.replace("\\", "/");

    }

    /**
     * 执行作业以依赖文件上传  By黄振
     * @param userId
     * @return
     * @throws UnsupportedEncodingException
     * @throws FileUploadException
     */
    public boolean executeJobUpload(String userId, Job job, HttpResult httpResult) throws UnsupportedEncodingException, FileUploadException {
        File file = new File(SAVE_PATH);
        // 判断文件保存目录是否存在
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
        // 使用Apache组件上传文件的步骤：
        // 1.创建一个DiskFileItemFactory
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 2.创建一个文件上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(maxSize);
        // 解决中文乱码
        upload.setHeaderEncoding("UTF-8");
        // 3.判断提交的数据是否合法
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 按照传统方法获取
            httpResult.setMessage("出错了，请联系管理员");
            httpResult.setResult(false);
            return false;
        }
        // 4.使用解析器上传数据，解析返回的是List<FileItem>,FileItem对应一个form表单
        List<FileItem> list = upload.parseRequest(request);
        /**
         * 解析上传的域
         */
        for (FileItem item : list) {
            /**
             * form表单域
             */
            if (item.isFormField()) {
                if ("algorithm".equals(item.getFieldName())) {
                    JSONObject jsonObject = JSONObject.fromObject(item.getString("UTF-8"));
                    try {
                        job.setName(jsonObject.getString("name"));
                        job.setCommand(jsonObject.getString("command"));
                        String scheduling_strategy = jsonObject.getString("scheduling_strategy");
                        switch (scheduling_strategy){
                            case "cpu可利用率最大":
                                scheduling_strategy = "ut";
                                break;
                            case "cpu可利用率最小":
                                scheduling_strategy = "-ut";
                                break;
                            case "内存剩余最大":
                                scheduling_strategy = "mem";
                                break;
                            case "内存剩余最小":
                                scheduling_strategy = "-mem";
                                break;
                            default:
                                break;
                        }
                        job.setStrategy(scheduling_strategy);
                        job.setJobPriority(jsonObject.getString("priority"));
                        job.setJobQueue(jsonObject.getString("job_queue"));
                        job.setNodeGroup(jsonObject.getString("node_group"));
                        job.setJobType(Boolean.parseBoolean(jsonObject.getString("work_style")));
                        job.setStartTime(jsonObject.getString("sTime"));
                        job.setEndTime(jsonObject.getString("eTime"));
                        if(!jsonObject.getString("memorynum").isEmpty()){
                            job.setMemoryUsage(jsonObject.getString("memorynum")+"M");
                        }
                        if(!jsonObject.getString("cpunum").isEmpty()){
                            job.setCPUkernelNumber(jsonObject.getString("cpunum"));
                        }
                        job.setUseGPU(Boolean.parseBoolean(jsonObject.getString("GPU")));
                        job.setUseMPI(Boolean.parseBoolean(jsonObject.getString("MPI")));
                        job.setMPINumber(jsonObject.getString("mpinum"));
                        job.setOsType(jsonObject.getString("osType"));
                        job.setUserId(userId);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        httpResult.setMessage("表单数据出错");
                        httpResult.setResult(false);
                        return false;
                    } catch (JSONException e) {
                        e.printStackTrace();
                        httpResult.setMessage("表单数据出错");
                        httpResult.setResult(false);
                        return false;
                    }
                }
            } else
            /**
             * 文件域
             */
            {
                String fileName = item.getName() + "";
                // 如果封装的上传文件
                String fileType = item.getName();
                if (fileType == null || "".equals(fileType.trim())) {
                    continue;
                }
                // 不同浏览器提交的文件名是不一样的，有的是带路径的
                // 处理文件路径部分，只保留文件名
                fileType = fileType.substring(fileType.lastIndexOf("/") + 1);
                fileType = fileType.substring(fileType.lastIndexOf("\\") + 1);
                fileType = fileType.substring(fileType.lastIndexOf("."), fileType.length());
                String path = SAVE_PATH;
                File directoryFile = new File(path);
                long fileSize = item.getSize();
                if (fileName.equals("") && fileSize == 0) {
                    this.isSuccess = false;
                    httpResult.setMessage("算法文件为空");
                } else {
                    try {
                        if (!directoryFile.exists()) {
                            directoryFile.mkdirs();
                        }
                        String jobHash = UUID.randomUUID().toString().substring(10);
                        String filePath = path+jobHash;
                        File f = new File(filePath);
                        f.mkdirs();
                        filePath += "/"+ fileName;
                        File uploadFile = new File(filePath);
                        item.write(uploadFile);
                        job.setJobHash(jobHash);
                        job.setDependentFiles(fileName);
                        job.setFileUri(filePath);
                        this.isSuccess = true;
                    } catch (Exception e) {
                        this.isSuccess = false;
                        httpResult.setMessage("出错了，请联系管理员");
                        e.printStackTrace();
                    }
                    // 删除临时文件
                    item.delete();
                }
            }
        }
        httpResult.setResult(this.isSuccess);
        return isSuccess;
    }
}
